<template>
  <el-popover
    v-model="visible"
    placement="bottom"
    trigger="click"
    popper-class="express-entrance__popper"
    v-if="isWorkbenchGray"
  >
    <div class="express-entrance__drag-wrap">
      <draggable
        v-bind="dragOptions"
        v-model="quickEntranceList"
        :disabled="!isSetting"
        handle=".sort-icon"
        tag="div"
        class="express-entrance__list"
      >
        <div
          class="express-entrance__list-item"
          v-for="item in quickEntranceList"
          :key="item.id"
          v-show="item.selected || isSetting"
          @click="openQuickTab(item)"
        >
          <i v-if="isSetting" class="iconfont icon-tuozhuaipaixu sort-icon" />
          <i :class="['iconfont', item.icon, 'type-icon']" />
          <span :class="['content', item.selected ? '' : 'not-selected-color']">
            {{ item.name }}
          </span>
          <el-switch
            v-if="isSetting"
            class="switch"
            v-model="item.selected"
          ></el-switch>
        </div>
      </draggable>
      <div class="express-entrance__save" @click="toggleSetting">
        {{ isSetting ? '保存' : '设置' }}
      </div>
    </div>
    <template #reference>
      <button
        slot="reference"
        type="button"
        class="express-entrance__button"
        @mouseenter="visible = true"
      >
        <span class="square">
          <i class="iconfont icon-add1"></i>
        </span>
      </button>
    </template>
  </el-popover>
</template>

<script>
import {
  getQuickEntrance,
  fetchInitialData,
  saveEntrance,
} from '@src/api/WorkbenchApi';
import { ref, defineComponent, unref, watch } from 'vue';
import draggable from 'vuedraggable';
import platform from '@src/platform';

const quickEntranceMap = {
  eventCreate: {
    entrance: 'event',
    icon: 'icon-caidan_fuwutai',
    id: 'event',
    name: '新建事件',
    url: '/event/edit',
  },
  taskCreate: {
    entrance: 'task',
    icon: 'icon-caidan_gongdanmokuai',
    id: 'task',
    name: '新建工单',
    url: '/task/edit',
  },
  customerCreate: {
    entrance: 'customer',
    icon: 'icon-caidan_kehumokuai',
    id: 'customer',
    name: '新建客户',
    url: '/customer/create',
  },
  productCreate: {
    entrance: 'product',
    icon: 'icon-caidan-chanpin',
    id: 'product',
    name: '新建产品',
    url: '/customer/product/create',
  },
  documentCreate: {
    entrance: 'wiki',
    icon: 'icon-read-fill',
    id: 'wiki',
    name: '新建知识库',
    url: '/wiki/create/page',
  },
  informationCreate: {
    entrance: 'informationAnnouncement',
    icon: 'icon-caidan_xinxiguanli',
    id: 'informationAnnouncement',
    name: '新建信息公告',
    url: '/info/notice/create/page',
  },
  scheduleCreate: {
    entrance: 'schedule',
    icon: 'icon-caidan-richengguanli',
    id: 'schedule',
    name: '新建日程',
    url: '/calendar?type=create',
  },
};

export default defineComponent({
  name: 'express-entrance',
  components: {
    draggable,
  },
  setup() {
    const visible = ref(false);
    const isWorkbenchGray = ref(false);
    const isSetting = ref(false);
    const quickEntranceList = ref([]);
    const loading = ref(false);
    const dragOptions = ref({
      animation: 200,
      ghostClass: 'ghost',
    });
    // 获取工作台灰度
    async function getWorkBenchGray() {
      const data = await fetchInitialData();
      isWorkbenchGray.value = data?.workbench;
    }

    watch(visible, () => {
      isSetting.value = false;
    });

    // 获取快捷入口列表
    async function getEntranceList() {
      try {
        await getWorkBenchGray();
        if (!unref(isWorkbenchGray)) return;
        let list = await getQuickEntrance();
        (list || []).forEach(
          item => (item.icon = quickEntranceMap[item.type]?.icon)
        );
        quickEntranceList.value = list;
      } catch (err) {
        console.warn('get entrance list error', err);
      }
    }

    // 切换编辑状态
    function toggleSetting() {
      if (unref(loading)) return;
      if (isSetting.value) {
        settingSave();
      } else {
        isSetting.value = true;
      }
    }

    async function settingSave() {
      try {
        loading.value = true;
        const params = unref(quickEntranceList)
          .filter(item => item.selected)
          .map(item => item.type);
        await saveEntrance(params);
        isSetting.value = false;
      } catch (err) {
        console.warn('save entrance error', err);
      } finally {
        loading.value = false;
      }
    }

    function hidePopper(){
      visible.value = false
    }

    // 打开对应快捷入口页面
    function openQuickTab(item) {
      if (unref(isSetting)) return;
      hidePopper()
      let url = quickEntranceMap[item.type]?.url;
      if(!url) return console.error(`type: ${item.type } url is not defined`)
      if (item.name === '新建日程') {
        url += `&random=${Math.random()}`;
      }
      platform.openTab({
        id: item.id,
        title: item.name,
        url,
        reload: true,
      });
    }

    getEntranceList();

    return {
      // 是否显示
      visible,
      // 工作台灰度
      isWorkbenchGray,
      // 是否设置模式
      isSetting,
      dragOptions,
      quickEntranceList,
      toggleSetting,
      openQuickTab,
      hidePopper,
    };
  },
});
</script>
<style lang="scss">
.express-entrance__popper {
  padding: 0;
  .express-entrance__drag-wrap {
    .express-entrance__list {
      padding: 10px 0;
    }
    .express-entrance__list-item {
      padding: 4px 4px;
      width: 100%;
      height: 32px;
      display: flex;
      align-items: center;
      cursor: pointer;
      user-select: none;
      &:hover {
        background: #f5f5f5;
      }
      .sort-icon {
        font-size: 14px;
        cursor: move;
        color: #BFBFBF;
      }
      .type-icon {
        margin-left: 8px;
        font-size: 14px;
        color: $color-primary-light-6;
      }
      .content {
        padding: 0 8px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .switch {
      }
    }
  }
  .express-entrance__save {
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: $color-primary;
    border-top: 1px solid #e8e8e8;
    cursor: pointer;
  }
}
.express-entrance__button {
  outline: none;
  border: none;
  width: 24px;
  height: 24px;
  background: $color-primary-light-6;
  border-radius: 4px;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: $color-primary-light-5;
  }
  i {
    font-size: 12px;
  }
}
</style>
